package com.zbec.mdrs.web;

import com.zbec.framework.core.vo.JqgridResponse;
import com.zbec.framework.core.vo.PageInfo;
import com.zbec.framework.security.entity.SysOrganization;
import com.zbec.framework.security.service.SecurityService;
import com.zbec.framework.security.vo.OrganizationVO;
import com.zbec.mdrs.constants.Constants;

import com.zbec.mdrs.entity.RecordEntity;
import com.zbec.mdrs.entity.discount.Discount;
import com.zbec.mdrs.service.*;
import com.zbec.mdrs.util.ResourceUtils;
import com.zbec.mdrs.vo.MbtVo;
import com.zbec.mdrs.vo.ReportFileVo;
import com.zbec.mdrs.vo.TxtBeanMapping;
import org.json.simple.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by fxl on 2015/10/28.
 */
@Controller
@RequestMapping(value = "/report")
public class ReportFileController extends  BaseController {

    @Autowired
    @Qualifier("discountBean")
    private TxtBeanMapping discountBean;
    @Autowired
    @Qualifier("loanBean")
    private TxtBeanMapping loanBean;
    @Autowired
    @Qualifier("draftsBean")
    private TxtBeanMapping draftsBean;
    @Autowired
    @Qualifier("entrustedLoantBean")
    private TxtBeanMapping entrustedLoantBean;
    @Autowired
    @Qualifier("guaranteeBean")
    private TxtBeanMapping guaranteeBean;


    @Autowired
    private ReportFileService reportFileService;
    @Autowired
    private LoanService loanService;
    @Autowired
    private DiscountService discountService;
    @Autowired
    private EntrustedLoanService entrustedLoanService;
    @Autowired
    private DraftsService draftsService;
    @Autowired
    private GuaranteeService guaranteeService;
    @Autowired
    private LogsService logsService;

    @Autowired
    private SecurityService securityService;


    @RequestMapping(value = "/toReport")
    public String toReport(HttpServletRequest request) {
            return "report/report_list";
    }

    @RequestMapping(value = "/reportList")
    @ResponseBody
    public JqgridResponse<ReportFileVo> findAllReportFile(PageInfo pageInfo,HttpServletRequest request) {
        return reportFileService.findAllReportFile(pageInfo);
    }

    @RequestMapping(value = "/toGenerate")
    public ModelAndView toGenerate(HttpServletRequest request) {
        ModelAndView view=new ModelAndView();
        OrganizationVO orgVo= securityService.getCurrentUserVO().getBranch();
        if(orgVo!=null && orgVo.getOrgType().equals(Constants.BANK_TYPE_FH)){
            List<OrganizationVO> voList=securityService.findByParentOrgId(orgVo.getId());
            if(voList==null){
                voList=new ArrayList<OrganizationVO>();
            }
            voList.add(0,orgVo);
            view.addObject("orgList",voList);
            view.addObject("isFh","true");
        }else {
            view.addObject("isFh","false");
            if(orgVo!=null){
                view.addObject("orgId",orgVo.getId());
            }
        }
        if(this.isUserReseted(securityService.getCurrentUserVO())){
            view.setViewName("system/editPassword");
        }else {
            view.setViewName("report/reportInput");
        }
        return view;
    }

    @RequestMapping(value = "/generate")
    @ResponseBody
   public String generate(MbtVo mbtVo,HttpServletRequest request){

        String[] bizChecked=mbtVo.getBusinessType().split(",");
       String sjsj=mbtVo.getBusinessDate().replace("-","");
        JSONObject object=new JSONObject();

       List list = null;
       TxtBeanMapping beanMapping = null;
        String userIp=this.getIPAddress(request);
        String  message="";

       for (int i = 0; i < bizChecked.length; i++) {
           String x = bizChecked[i];
           if (Constants.BUSINESS_TYPE_LOAN.equals(x)) {
               beanMapping = loanBean;
               list = loanService.getActiveLoanByYwMonth(sjsj,mbtVo.getOrgId());
           }else if (Constants.BUSINESS_TYPE_DISCOUNT.equals(x)) {
               beanMapping = discountBean;
               list = discountService.getActiveDiscountByYwMonth(sjsj,mbtVo.getOrgId());
           }else if (Constants.BUSINESS_TYPE_DRAFTS.equals(x)) {
               beanMapping = draftsBean;
               list = draftsService.getActiveDraftsByYwMonth(sjsj,mbtVo.getOrgId());
           }else if (Constants.BUSINESS_TYPE_ENTRUSTED_LOAN.equals(x)) {
               beanMapping = entrustedLoantBean;
               list = entrustedLoanService.getActiveEntrustedLoanByYwMonth(sjsj,mbtVo.getOrgId());
           }else if (Constants.BUSINESS_TYPE_GUARANTEE.equals(x)) {
               beanMapping = guaranteeBean;
               list = guaranteeService.getActiveGuaranteeByYwMonth(sjsj,mbtVo.getOrgId());
           }

           if (list==null|| list.size() == 0) {
                message=message+ResourceUtils.getLocaleString("message."+x+".nodatafailure")+"===";
                logsService.handleBuzLogData(userIp,"logs.type."+x,"logs.operation.export",false, ResourceUtils.getLocaleString("message."+x+".nodatafailure"));
           } else if(findErrorRecord(list)){
                message=message+ResourceUtils.getLocaleString("message."+x+".errordatafailure")+"===";
               logsService.handleBuzLogData(userIp, "logs.type."+x, "logs.operation.export", false, ResourceUtils.getLocaleString("message." + x + ".errordatafailure"));
           } else{
               String[] date= mbtVo.getBusinessDate().split("-");
               Boolean r = reportFileService.generateFileByMonth(list,date[0],date[1], beanMapping,request.getSession().getServletContext().getRealPath(Constants.REPORT_FILE_FOLDER),userIp);
               if (r) {
                   message=message+ResourceUtils.getLocaleString("message."+x+".generatesuccess")+"===";
                   logsService.handleBuzLogData(userIp,"logs.type."+x,"logs.operation.export",true, ResourceUtils.getLocaleString("message."+beanMapping.getBizKey()+".generatesuccess"));


               }
               else{
                   message=message+ResourceUtils.getLocaleString("message."+x+".generatefailure")+"===";
                   logsService.handleBuzLogData(userIp, "logs.type."+x, "logs.operation.export", false, ResourceUtils.getLocaleString("message." + x + ".generatefailure"));
               }
           }
       }
        object.put("message",message);


       return object.toJSONString();
   }

    private boolean findErrorRecord(List list) {
        for(int j=0;j<list.size();j++) {
            RecordEntity record = (RecordEntity) list.get(j);
            if (Constants.EXIST_ERROR_YES.equals(record.getExistError())) {
                return true;
            }
        }
        return false;
    }

}
